import re
import asyncio

from .basic import BasicSchema

from telethon.tl.functions.messages import GetBotCallbackAnswerRequest
from telethon.tl.functions.contacts import BlockRequest


class Bot_Loop(BasicSchema):
    def __init__(self, client, new_client, turple_rounds, CONST_NAMED_BOT):
        super().__init__(client, new_client, turple_rounds, CONST_NAMED_BOT)

    async def loop(self):
        self.logging.info("Started miner bots")
        while True:
            self.logging.info("New bot circle")
            await self.rand_sleep(1, 2)
            allmsg = await self.client.get_messages(self.tegmo, limit=2)
            msg = allmsg[0]
            if self.round_loop > self.CONST_ROUNDS_TO_SLEEP:
                self.round_loop = 0
                self.logging.info("Sleep for many round")
                await self.rand_sleep(3600, 3600)
                # await self.withdraw()
            self.round_loop += 1
            if re.search(r'Press the "Message bot"', msg.message):
                url = msg.reply_markup.rows[0].buttons[0].url
                username = url.split("/")[-1].split("?")[0]
                try:
                    async with self.client.conversation(username) as conv:
                        await conv.send_message("/start")
                        try:
                            resp = await conv.get_response()
                        except asyncio.exceptions.TimeoutError:
                            self.logging.info("Dont work other bot, continue...")
                            await self.client(BlockRequest(username))
                            await self.client.delete_dialog(username)
                            button_data = msg.reply_markup.rows[1].buttons[1].data
                            message_id = msg.id
                            await self.client(
                                GetBotCallbackAnswerRequest(
                                    self.tegmo, message_id, data=button_data
                                )
                            )
                            continue
                        except DeprecationWarning:
                            pass
                        self.logging.info("Forwarding message...")
                        await self.client.forward_messages(self.tegmo, resp)
                        self.logging.info("Forward ok, sleep...")
                        await self.rand_sleep(2, 3)
                        await self.client(BlockRequest(username))
                        await self.client.delete_dialog(username)
                        self.logging.info(
                            "Successful blocking and delete chat, continue"
                        )
                        continue
                except:
                    self.logging.info(
                        "Dont work, bad url or this not a bot, continue..."
                    )
                    button_data = msg.reply_markup.rows[1].buttons[1].data
                    message_id = msg.id
                    try:
                        await self.client(
                            GetBotCallbackAnswerRequest(
                                self.tegmo, message_id, data=button_data
                            )
                        )
                    except:
                        allmsg = await self.client.get_messages(self.tegmo, limit=2)
                        msg = allmsg[0]
                        await self.client(
                            GetBotCallbackAnswerRequest(
                                self.tegmo, message_id, data=button_data
                            )
                        )
                    continue
            elif re.search(r"Sorry", msg.message):
                # if self.total_sorry_round > 25:
                #     self.total_sorry_round = 0
                #     self.logging.info("Sleep for many sorry responses..")
                #     await self.rand_sleep(
                #         self.CONST_SORRY_SLEEP, self.CONST_SORRY_SLEEP
                #     )
                #     continue
                if self.sorry_round > 3:
                    self.sorry_round = 0
                    return self.total_sorry_round, self.round_loop
                else:
                    self.sorry_round += 1
                    self.total_sorry_round += 1
                    await self.client.send_message(
                        f"{self.CONST_NAMED_BOT} Click Bot", "/bots"
                    )
                    continue
            else:
                await self.client.send_message(
                    f"{self.CONST_NAMED_BOT} Click Bot", "/bots"
                )
